package dp05.leertaak1.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import dp05.leertaak1.server.protocol.Protocol;
import dp05.leertaak1.server.protocol.ProtocolDbAvailable;
import dp05.leertaak1.server.protocol.ProtocolDbUnavailable;

public class ClientListener implements Runnable
{
    private ServerSocket socket;
    private final int PORT = 1337;

    public ClientListener()
    {
        try
        {
            socket = new ServerSocket(PORT);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void run()
    {
        try
        {
            while (true)
            {
                handleNewClient(socket.accept());
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void handleNewClient(Socket client) throws IOException
    {
        Protocol protocol = null;
        if(Server.isDatabaseAvailable())
        {
            protocol = new ProtocolDbAvailable();
            System.out.println("DB available");
        }
        else
        {
            protocol = new ProtocolDbUnavailable();
            System.out.println("DB not available");
        }
        ClientHandler clientHandler = new ClientHandler(client, protocol);
        Server.addClient(clientHandler);
        Thread clientThread = new Thread(clientHandler);
        clientThread.start();
    }

}
